#include "vkclient.h"
#include "vkparser.h"
#include <qdebug.h>

VKChecker::VKChecker(QString email, QString pass)
{
    qEmail = email.replace("@", "%40", Qt::CaseInsensitive);
    qPass = pass;
    qLocation = "/";
    logged = false;
    chttp = new HttpClient("login.vk.com");
    chttp->addCookies("remixlang=3; remixchk=5; ");
    chttp->setTimeout(5000);
}

VKChecker::~VKChecker()
{
    delete chttp;
}

void VKChecker::setProxyInfo(bool useProxy, QString proxyHost, int proxyPort, bool useAuthorization, QString proxyUserName, QString proxyPassword)
{
    chttp->setProxyInfo(useProxy, proxyHost, proxyPort, useAuthorization, proxyUserName, proxyPassword);
}

QString VKChecker::getNewMessages(QLabel *lab)
{
    QString result = "";
    if (!logged)
    {
        LoginResult res = login();
        switch (res)
        {
            case LoginOK: {
                    logged = true;
                    break;
                }
            case LoginConnectionFailed: {
                    logged = false;
                    lab->setText("<font color='white'>Connection to server failed</font>");
                    return "Error connect";
                }
            case LoginIncorrectInfo: {
                    logged = false;
                    lab->setText("<font color='white'>Incorrect login/password.</font>");
                    return "Error login";
                }
            case LoginUnknownError: {
                    logged = false;
                    lab->setText("<font color='white'>Unknown error</font>");
                    return "Error wtf";
                }
        }
    }
    // Getting home page...
    QString data = getHomePage();
    if ( chttp->response != 200 )
    {
        lab->setText("<font color='white'>Unknown error.</font>");
        logged = false;
        return "Error wtf";
    }
    VkParser parser(data);
    ParseUnreadMsgResult parseRes = parser.parseUnreadMsgCount();
    int co = parser.getUnreadNum();
    switch (parseRes)
    {
        case parseOk: {
                QString count = QString::number(co, 10);
                if (co == 0)
                    lab->setText("<font color='white'>You haven't unread<br>messages.</font>");
                else
                {
                    lab->setText("<font color='white'>You have "+count+" unread<br>messages</font>");
                }
                return count;
                break;
            }
        case parseIncorrectInfo: {
                return "Error login";
                break;
            }
        case parseUnknownError: {
                return "Error wtf";
                break;
            }
        default: {
                return "Error wtf";
                break;
            }
    }
    return ""; // to make compiler happy
}

LoginResult VKChecker::login()
{
    QString postRequest1 = "email="+qEmail+"&pass="+qPass;
    // Trying to get login page till we did it xD
    bool ok = false;
    while (!ok)
    {
        chttp->doRequest("login.vk.com", "/?act=login&to=&from_host=pda.vkontakte.ru&pda=1", postRequest1.toUtf8());
        chttp->wait();
        ok = chttp->finished || ok;
    }
    QRegExp re("<input type='hidden' name='s' value='([^']+)' />");
    if (re.indexIn(chttp->qData) == -1)
        return LoginUnknownError;

    QString s = re.cap(1);
    QString postRequest2 = "s="+s+"&op=slogin&redirect=1&expire=0&to=";
    ok = false;
    while (!ok)
    {
        chttp->doRequest("pda.vkontakte.ru", "/login", postRequest2.toUtf8());
        chttp->wait();
        ok = chttp->finished || ok;
    }
    // Analyzing server answer..
    switch (chttp->response)
    {
        case 200: {
                return  LoginIncorrectInfo;
                break;
            }

        case 302: {
                if (chttp->qLocation.indexOf("err=") != -1)
                    return LoginIncorrectInfo;
                else
                    return LoginOK;
                break;
            }

        case 0: {
                return LoginConnectionFailed;
                break;
            }

        default: {
                //TODO: write some debug info here; add more variants
                return LoginUnknownError;
                break;
            }
    }
    return LoginUnknownError; // to make compiler happy
}

QString VKChecker::getHomePage()
{
    srand(time(NULL));
    qLocation = "/?"+QString::number(rand()%20000, 10);
    bool ok = false;
    while (!ok)
    {
        chttp->doRequest("pda.vkontakte.ru", qLocation);
        chttp->wait();
        if (chttp->finished)
            ok = true;
        chttp->finished=false;
    }
    return chttp->qData;
}
